package com.example.manager.handler;

import com.alibaba.fastjson.JSON;

import com.example.common.utils.AuthContextUtil;
import com.example.model.constant.RedisConstant;
import com.example.model.vo.common.Result;
import com.example.model.vo.common.ResultCodeEnum;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.concurrent.TimeUnit;

/**
 * @Description: 拦截器
 * @Version: 1.0
 *
 *
 */
@Component
public class LoginAuthInterceptor implements HandlerInterceptor {

    @Autowired
    private RedisTemplate<String,String> redisTemplate ;


    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 获取请求方式
        String method = request.getMethod();
        if("OPTIONS".equals(method)) {      // 如果是跨域预检请求，直接放行
            return true ;
        }

        // 获取token
        String token = request.getHeader("token");
        if (StringUtils.isEmpty(token)){
            responseNoLoginInfo(response);
            return false;
        }

        // 如果token不为空，那么此时验证token的合法性
        String s = redisTemplate.opsForValue().get(RedisConstant.USER_LOGIN + token.replace("Bearer " , ""));
        if (StringUtils.isEmpty(s)){
            responseNoLoginInfo(response);
            return false;
        }

        // 将token数据存储到ThreadLocal中
        AuthContextUtil.setJwtToken(s);

        // 重置Redis中的用户数据的有效时间
        redisTemplate.expire(RedisConstant.USER_LOGIN + token , 30 , TimeUnit.MINUTES) ;

        return true;
    }

    //响应208状态码给前端
    private void responseNoLoginInfo(HttpServletResponse response) {
        Result<Object> result = Result.build(null, ResultCodeEnum.LOGIN_AUTH);
        PrintWriter writer = null;
        response.setCharacterEncoding("UTF-8");
        response.setContentType("text/html; charset=utf-8");
        try {
            writer = response.getWriter();
            writer.print(JSON.toJSONString(result));
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (writer != null) writer.close();
        }
    }


    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        AuthContextUtil.removeJwtToken();  // 移除threadLocal中的数据
    }



}
